<template>
  <div class="cluster-container">
    <div class="cluster-header">
      <el-image
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/clusterManage.png')"
      ></el-image>
      <div class="title">
        集群管理
        <div class="title-content">
          对多集群信息进行统一管理和协调，为容器管理平台提供部署环境，以实现高可用性和资源优化
        </div>
      </div>
    </div>
    <div class="top-content">
      <div class="cluster-info">
        <div class="cluster-operate">
          <span class="keyword">关键词：</span>
          <el-input
            placeholder="请输入名称、描述"
            v-model="searchInput"
            style="width: 20%"
            prefix-icon="el-icon-search"
            clearable
            @input="filterClusterList"
          >
          </el-input>
          <!-- <el-button icon="el-icon-search" circle @click="filterClusterList"></el-button> -->
          <div class="right-menu">
            <!--                <el-button style="width: 100px;background:#304156;color: #fff;" type="primary" plain @click="refreshPage">刷新</el-button>-->
            <el-button
              type="primary"
              @click="uploadDialogVisible = true"
              class="el-button-primary-style"
              >添加
            </el-button>
          </div>
          <el-button
            v-if="isRowSelected"
            type="danger"
            @click="deleteSelectedRow"
            >删除
          </el-button>
        </div>
        <div class="cluster-table">
          <el-table
            ref="multipleTable"
            :data="filteredTableDate.length > 0 ? filteredTableDate : tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            height="60vh"
          >
            <!--            :cell-style="{ textAlign: 'center' }"-->
            <!--            :header-cell-style="{ textAlign: 'center' }"-->
            <el-table-column
              type="selection"
              width="60"
              align="center"
            ></el-table-column>
            <el-table-column label="名称" width="150">
              <template slot-scope="scope">
                <el-tooltip
                  effect="dark"
                  :content="scope.row.clusterZhname"
                  placement="bottom"
                  popper-class="myTooltipClass"
                >
                  <div class="descSpan">
                    {{ scope.row.clusterZhname }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="clusterUrl" label="集群地址" width="150">
            </el-table-column>
            <el-table-column label="集群描述">
              <template slot-scope="scope">
                <el-tooltip
                  effect="dark"
                  :content="scope.row.clusterDescription"
                  placement="bottom"
                  popper-class="myTooltipClass"
                  :disabled="isShowTooltip"
                >
                  <div class="descSpan" @mouseover="onMouseOver($event)">
                    {{ scope.row.clusterDescription }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="创建模式" width="120">
              <template slot-scope="scope">
                <span>
                  {{ getCreateModel(scope.row.isAuto) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.updateTime }}
              </template>
            </el-table-column>
            <el-table-column label="详细" width="100">
              <template slot-scope="scope">
                <el-button
                  style="background: rgb(221 220 244); padding: 6px"
                  @click="looklook(scope.row)"
                  >查看
                </el-button>
                <!-- <el-button size="small" @click="echartsDialogVisible = true">查看</el-button> -->
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="padding: 0"
                  @click="editCluster(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  style="padding: 0"
                  @click="testLink(scope.row)"
                  >连接测试</el-button
                >
                <!--                <el-button type="text" style="color:#F56C6C; padding: 0" @click="deleteCluster(scope.row)">删除-->
                <!--                </el-button>-->
                <el-popconfirm
                  title="此操作将永久删除该集群, 是否确认？"
                  @confirm="deleteCluster(scope.row)"
                >
                  <el-button
                    type="text"
                    slot="reference"
                    style="padding: 0; color: #f56c6c"
                  >
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 10px; float: right">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="page.total"
            :page-size="page.pageSize"
            :page.sync="page"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <div class="add-cluster">
      <el-dialog
        title="添加集群"
        :visible.sync="uploadDialogVisible"
        width="30%"
        :before-close="beforeCloseUploadDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div style="width: 100%; display: flex; justify-content: center">
          <el-form
            ref="uploadForm"
            :rules="rules"
            :model="uploadInfo"
            label-width="80px"
          >
            <el-form-item label="集群名称" prop="clusterZhname">
              <el-input
                v-model="uploadInfo.clusterZhname"
                placeholder="请输入长度小于24的字符串"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="集群地址" prop="clusterUrl">
              <el-input
                v-model="uploadInfo.clusterUrl"
                placeholder="请输入IP地址格式内容"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="集群描述" prop="clusterDescription">
              <el-input
                v-model="uploadInfo.clusterDescription"
                placeholder="请输入长度小于512的字符"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 2 }"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="Token" prop="clusterToken">
              <el-input
                v-model="uploadInfo.clusterToken"
                placeholder="请输入Token内容"
                type="textarea"
                :rows="2"
                style="width: 300px"
              >
              </el-input>
              <el-tooltip
                class="item"
                effect="dark"
                content="点击查看获取Token获取方式"
                placement="bottom-start"
              >
                <i
                  class="el-icon-question"
                  style="font-size: 25px; color: slategray; margin-left: 8px"
                  @click="openTipDialog"
                ></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="监控端口" prop="grafanaPort">
              <el-input
                v-model="uploadInfo.grafanaPort"
                placeholder="请输入监控端口"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <!--          <el-form-item label="配置文件" prop="file" required>-->
            <!--            <el-upload-->
            <!--              class="uploadDiv"-->
            <!--              :action="uploadPath"-->
            <!--              :before-upload="beforeUpload"-->
            <!--              :limit="1"-->
            <!--              :file-list="fileList"-->
            <!--              :on-error="onUploadError"-->
            <!--              :disabled="fileList.length === 1"-->
            <!--              :destroy-on-close="true"-->
            <!--            >-->
            <!--              <el-button class="upload-button" size="small" type="primary" style="float: left;">点击上传</el-button>-->
            <!--            </el-upload>-->
            <!--          </el-form-item>-->
            <el-form-item>
              <div style="justify-content: right; display: flex">
                <el-button
                  type="primary"
                  @click="addCluster"
                  class="el-button-primary-style"
                  >确定
                </el-button>
                <el-button
                  type="primary"
                  @click="closeUploadDialog"
                  class="el-button-primary-style"
                  >取消
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <div class="update-cluster">
      <el-dialog
        title="修改集群信息"
        :visible.sync="updateDialogVisible"
        width="30%"
        :before-close="beforeCloseUpdateDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div style="width: 100%; display: flex; justify-content: center">
          <el-form
            :model="updateInfo"
            :rules="updateRules"
            label-width="80px"
            ref="updateForm"
          >
            <el-form-item label="集群名称" prop="clusterZhname">
              <el-input
                v-model="updateInfo.clusterZhname"
                placeholder="请输入长度小于24的字符串"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="集群地址" prop="clusterUrl">
              <el-input
                v-model="updateInfo.clusterUrl"
                placeholder="请输入IP地址格式内容"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="集群描述" prop="clusterDescription">
              <el-input
                v-model="updateInfo.clusterDescription"
                placeholder="请输入长度小于512的字符"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 2 }"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="监控端口" prop="grafanaPort">
              <el-input
                v-model="updateInfo.grafanaPort"
                placeholder="请输入监控端口"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <div style="justify-content: right; display: flex">
                <el-button
                  type="primary"
                  @click="updateCluster"
                  class="el-button-primary-style"
                  >确定
                </el-button>
                <el-button
                  type="primary"
                  @click="updateDialogVisible = false"
                  class="el-button-primary-style"
                  >取消
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="集群信息"
        :visible.sync="echartsDialogVisible"
        width="80%"
        :before-close="beforeCloseUploadDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div class="cluster-detail">
          <span style="width: 20%; text-align: center; margin-right: 10%">
            集群名称: {{ this.lookInfo.clusterZhname }}</span
          >
          <span style="text-align: center">|</span>
          <span style="width: 25%; text-align: center"
            >Kubernetes版本: {{ this.lookInfo.version }}</span
          >
          <span style="text-align: center">|</span>
          <span style="width: 25%; margin-left: 2%; text-align: center"
            >创建时间: {{ this.lookInfo.updateTime }}</span
          >
        </div>
        <div style="display: flex; height: 320px; justify-content: center">
          <div ref="cpuChart" style="width: 80%"></div>
          <div ref="memoryChart" style="width: 80%"></div>
          <div ref="podChart" style="width: 80%"></div>
        </div>
        <div>
          <el-table
            :data="clusterTableData"
            stripe
            style="width: 100%"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
            height="24vh"
          >
            <el-table-column prop="nodeName" label="主机名" width="180">
            </el-table-column>
            <el-table-column prop="nodeAddress" label="节点IP" width="180">
            </el-table-column>
            <el-table-column prop="nodeRole" label="节点类型" width="180">
            </el-table-column>
            <el-table-column prop="nodeStatus" label="节点状态" width="180">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.nodeStatus === 'True'">
                  HEALTH
                </el-tag>
                <el-tag type="danger" v-else> UNHEALTH </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="CPU(核)" width="180">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.nodeCpuUsed }}/{{ scope.row.nodeCpuTotal }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="内存(GB)" width="180">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.nodeMemoryUsed }}/{{ scope.row.nodeMemoryTotal }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="POD(个)">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.nodeUsedPod }}/{{ scope.row.nodePod }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-bottom: 10px; margin-top: 10px; float: right">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="clusterPage.total"
            :page-size="clusterPage.pageSize"
            :page.sync="clusterPage"
            @current-change="changeClusterPage"
          />
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="生成Token" :visible.sync="openTokenDialog" width="60%">
        <create-token-method></create-token-method>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="openTokenDialog = false"
            class="el-button-primary-style"
            >关 闭</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import CreateTokenMethod from "@/views/cluster-manage/createTokenMethod.vue";

export default {
  name: "ClusterManage",
  components: { CreateTokenMethod },
  data() {
    return {
      searchInput: "",
      uploadDialogVisible: false,
      updateDialogVisible: false,
      echartsDialogVisible: false,
      chart: null,
      fileList: [],
      isRowSelected: false,
      tableData: [],
      mulipleSelection: [],
      filteredTableDate: [], //搜索结果
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      tmpPage: {
        filterKey: "",
        pageNum: 1,
        pageSize: 10,
      },
      filterPage: {
        filterKey: "aaa",
        pageNum: 1,
        pageSize: 10,
      },
      detail: {
        id: "",
      },
      uploadInfo: {
        clusterZhname: "",
        clusterUrl: "",
        clusterDescription: "",
        // file: null,
        clusterToken: "",
        grafanaPort: null,
      },
      updateInfo: {
        clusterZhname: "",
        clusterUrl: "",
        clusterDescription: "",
        // file: null,
        grafanaPort: null,
      },
      lookInfo: {
        clusterZhname: "",
        version: "",
        updateTime: "",
      },
      echartsInfo: {
        cpuTotal: 0,
        cpuUsed: 0,
        memoryTotal: 0,
        memoryUsed: 0,
        podTotal: 0,
        podUsed: 0,
      },
      topic: "",
      nameInput: "",
      addressInput: "",
      descriptionInput: "",
      baseUploadPath: "/gv-kube/resource/cluster/upload",
      uploadPath: "/gv-kube/resource/cluster/upload",
      // 校验
      namePattern: /^[\u4E00-\u9FA5a-zA-Z0-9]{1,24}$/, // 中文名称，长度小于24
      addressPattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, // IP地址格式
      descriptionPattern: /^.{0,128}$/, // 中文描述  长度小于128
      file: "",
      rules: {
        clusterZhname: [
          { required: true, message: "请输入集群名称", trigger: "blur" },
          {
            min: 2,
            max: 24,
            message: "长度在 2 到 24 个字符",
            trigger: ["blur", "change"],
          },
        ],
        clusterUrl: [
          { required: true, message: "请输入集群地址", trigger: "blur" },
          {
            pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
            message: "请输入正确的集群地址，如192.168.1.1",
            trigger: ["blur", "change"],
          },
        ],
        clusterDescription: [
          {
            max: 512,
            message: "长度小于 512 个字符",
            trigger: ["blur", "change"],
          },
        ],
        clusterToken: [
          { required: true, message: "请输入 Token 内容", trigger: "blur" },
        ],
        grafanaPort: [
          // {required: true, message: "请输入端口大小", trigger: "blur"},
          {
            // pattern: /^([0-9])*$/,
            pattern:
              /^([1-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
            message: "监控端口在1-65535之间",
            trigger: ["blur", "change"],
          },
        ],
      },
      updateRules: {
        clusterZhname: [
          { required: true, message: "请输入集群名称", trigger: "blur" },
          {
            min: 2,
            max: 24,
            message: "长度在 2 到 24 个字符",
            trigger: ["blur", "change"],
          },
        ],
        clusterUrl: [
          { required: true, message: "请输入集群地址", trigger: "blur" },
          {
            pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
            message: "请输入正确的集群地址，如192.168.1.1",
            trigger: ["blur", "change"],
          },
        ],
        clusterDescription: [
          {
            max: 512,
            message: "长度小于 512 个字符",
            trigger: ["blur", "change"],
          },
        ],
        grafanaPort: [
          // {required: true, message: "请输入端口大小", trigger: "blur"},
          {
            // pattern: /^([0-9])*$/,
            pattern:
              /^([1-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
            message: "监控端口在1-65535之间",
            trigger: ["blur", "change"],
          },
        ],
      },
      clusterTableData: [],
      clusterTableData1: [],
      clusterPage: {
        pageSize: 3,
        currentPage: 1,
        total: 0,
      },
      openTokenDialog: false,
      isShowTooltip: false,
    };
  },
  methods: {
    handleEchartsDialogVisibleChange(visible) {
      if (visible) {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
    onMouseOver(event) {
      const ev = event.target;
      const evWeight = ev.scrollWidth;
      const contentWidth = ev.clientWidth;
      if (evWeight > contentWidth) {
        this.isShowTooltip = false;
      } else {
        this.isShowTooltip = true;
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.isRowSelected = val.length > 0;
    },
    editCluster(row) {
      // 寻找原始数据的索引
      this.updateDialogVisible = true; // 打开编辑弹窗

      const clusterZhname = row.clusterZhname;
      const clusterUrl = row.clusterUrl;
      const clusterDescription = row.clusterDescription;
      // 更新 updateInfo 对象的属性值
      this.updateInfo = {
        id: row.id,
        clusterZhname: clusterZhname,
        clusterUrl: clusterUrl,
        clusterDescription: clusterDescription,
        grafanaPort: row.grafanaPort,
      };
    },
    testLink(row) {
      this.$message.info("开始进行测试，请稍等");
      this.$clusterManageApi.connectClusterbyId(row.id).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.data);
        }
      });
    },
    // 确定修改
    updateCluster() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          this.$clusterManageApi
            .updateClusterInfo(this.updateInfo)
            .then((res) => {
              if (res && res.code === 200) {
                // 清空输入框
                this.nameInput = "";
                this.addressInput = "";
                this.descriptionInput = "";
                // 编辑保存成功后刷新页面
                this.getAllClusterByPage();
                this.closeUploadDialog();
                this.$message.success(res.data);
              }
            })
            .catch((error) => {
              this.$message.error("修改失败：" + error.message);
            });
        } else {
          this.$message.error("请检查数据");
          return false;
        }
      });
    },

    initChart() {
      // 创建ECharts实例
      const cpuChart = echarts.init(this.$refs.cpuChart);
      const memoryChart = echarts.init(this.$refs.memoryChart);
      const podChart = echarts.init(this.$refs.podChart);
      // 计算已使用量占总量的百分比
      const cpuUsagePercentage = (
        (this.echartsInfo.cpuUsed / this.echartsInfo.cpuTotal) *
        100
      ).toFixed(0);
      const memoryUsagePercentage = (
        (this.echartsInfo.memoryUsed / this.echartsInfo.memoryTotal) *
        100
      ).toFixed(0);
      const podUsagePercentage = (
        (this.echartsInfo.podUsed / this.echartsInfo.podTotal) *
        100
      ).toFixed(0);

      // 设置ECharts配置项
      const cpuOption = {
        series: [
          {
            name: "CPU",
            type: "gauge",
            radius: "80%",
            progress: {
              show: true,
            },
            detail: {
              valueAnimation: true,
              formatter: `\n\n\n\n\n已使用${this.echartsInfo.cpuTotal}核中的${this.echartsInfo.cpuUsed}核`,
              // offsetCenter: [0, '60%'],
              textStyle: {
                fontSize: 16,
              },
            },
            axisLabel: {
              formatter: "{value}%",
            },
            data: [
              {
                value: cpuUsagePercentage,
                name: `CPU\n${cpuUsagePercentage}%`,
              },
            ],
          },
        ],
      };

      const memoryOption = {
        series: [
          {
            type: "gauge",
            radius: "80%",
            progress: {
              show: true,
            },
            detail: {
              valueAnimation: true,
              formatter: `\n\n\n\n\n已使用${this.echartsInfo.memoryTotal}GB中的${this.echartsInfo.memoryUsed}GB`,
              // formatter: `${memoryUsagePercentage}%`,
              // offsetCenter: [0, '60%'],
              textStyle: {
                fontSize: 16,
              },
            },
            axisLabel: {
              formatter: "{value}%",
            },
            data: [
              {
                value: memoryUsagePercentage,
                name: `内存\n${memoryUsagePercentage}%`,
              },
            ],
          },
        ],
      };

      const podOption = {
        series: [
          {
            type: "gauge",
            radius: "80%",
            progress: {
              show: true,
            },
            detail: {
              valueAnimation: true,
              formatter: `\n\n\n\n\n已使用${this.echartsInfo.podTotal}个中的${this.echartsInfo.podUsed}个`,
              // offsetCenter: [0, '60%'],
              textStyle: {
                fontSize: 16,
              },
            },
            axisLabel: {
              formatter: "{value}%",
            },
            data: [
              {
                value: podUsagePercentage,
                name: `Pod\n${podUsagePercentage}%`,
              },
            ],
          },
        ],
      };

      // 使用配置项显示图表
      cpuChart.setOption(cpuOption);
      memoryChart.setOption(memoryOption);
      podChart.setOption(podOption);
    },
    // 分页获取所有集群信息
    getAllClusterByPage() {
      this.$clusterManageApi
        .pageGetCluster(this.tmpPage)
        .then((res) => {
          if (res && res.code === 200) {
            this.tableData = res.data.records;
            this.page.total = res.data.total;
            this.page.pageSize = res.data.pageSize;
            this.detail.id = res.data.records[0].id;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    // 搜索过滤展示
    filterClusterList() {
      this.tmpPage.filterKey = this.searchInput;
      this.tmpPage.pageNum = 1;
      this.tmpPage.pageSize = 10;
      this.$clusterManageApi
        .filterCluster(this.tmpPage)
        .then((res) => {
          // console.log("111");
        })
        .catch((error) => {
          this.$message.error("搜索失败：" + error.message);
          console.log(error.message);
        });
      this.getAllClusterByPage();
    },

    // 选中数据 - 删除
    deleteSelectedRow() {
      this.$confirm("此操作将永久删除该集群, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const selectedRowsIds = this.multipleSelection.map((row) => row.id);
          this.$clusterManageApi.delectCluster(selectedRowsIds).then((res) => {
            this.tableData = this.tableData.filter(
              (row) => !selectedRowsIds.includes(row.id)
            );
            this.multipleSelection = [];
            this.$message.success("删除成功");
          });
          // 清空选中的行
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击删除 - 删除
    deleteCluster(row) {
      // this.$confirm('此操作将永久删除该集群信息, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   const selectedRowId = [String(row.id)]; // 创建字符串数组并将 row.id 添加到数组中
      //   this.$clusterManageApi.delectCluster(selectedRowId).then(res => {
      //     this.$message.success('删除成功');
      //     this.getAllClusterByPage();
      //   });
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   });
      // });

      const selectedRowId = [String(row.id)]; // 创建字符串数组并将 row.id 添加到数组中
      this.$clusterManageApi.delectCluster(selectedRowId).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("删除成功");
          this.getAllClusterByPage();
        }
      });
    },

    looklook(info) {
      console.log("获取到对应行的id", info.id);
      this.lookInfo.clusterZhname = info.clusterZhname;
      // 版本
      this.$clusterManageApi
        .getClusterBasicinformationByid(info.id)
        .then((res) => {
          if (res && res.code === 200) {
            this.clusterTableData1 = [...res.data];
            console.log("clusterTableData1", this.clusterTableData1);
            // this.clusterPage.total = res.data.length;
          }
          this.clusterTableData = this.clusterTableData1.slice(
            0,
            this.clusterPage.pageSize
          );
          this.clusterPage.total = this.clusterTableData1.length;
        });
      // 时间
      this.lookInfo.updateTime = info.updateTime;
      this.$clusterManageApi.getClusterDetail(info.id).then((res) => {
        this.lookInfo.version = res.data.version;
        this.echartsInfo.cpuTotal = res.data.cpuTotal;
        this.echartsInfo.cpuUsed = res.data.cpuUsed;
        this.echartsInfo.memoryTotal = res.data.memoryTotal;
        this.echartsInfo.memoryUsed = res.data.memoryUsed;
        this.echartsInfo.podTotal = res.data.podTotal;
        this.echartsInfo.podUsed = res.data.podUsed;
        // console.log(re);
        // if (res && res.code === 200) {
        //   this.tableData = res.data.records
        //   this.page.total = res.data.total
        //   this.id = res.data.id
        // }
        this.echartsDialogVisible = true;
        this.handleEchartsDialogVisibleChange(this.echartsDialogVisible);
      });
    },
    // 更换页数
    changePage(currentPage) {
      this.page.currentPage = currentPage;
      this.tmpPage.pageNum = currentPage;
      this.getAllClusterByPage();
    },
    // 更换页数
    changeClusterPage(currentPage) {
      console.log(currentPage);
      this.clusterPage.currentPage = currentPage;
      this.clusterTableData = [
        ...this.clusterTableData1.slice((currentPage - 1) * 4, currentPage * 4),
      ];
      console.log(this.clusterTableData);
      console.log(this.clusterTableData1);
    },
    closeUploadDialog() {
      this.fileList = [];
      this.uploadDialogVisible = false;
      this.echartsDialogVisible = false;
      this.updateDialogVisible = false;
      this.uploadInfo = {
        clusterZhname: "",
        clusterUrl: "",
        clusterDescription: "",
        // file: null,
        clusterToken: "",
      };
    },
    beforeUpload(file) {
      const isLt2G = file.size / 1024 / 1024 < 2048;
      if (!isLt2G) {
        this.$message.error("上传文件大小不能超过 2048MB!");
      } else {
        this.fileList.push(file);
        console.log("this.fileList", this.fileList[0]);
      }
      return false;
    },
    onUploadError(error) {
      this.$message.error("文件上传失败：" + error);
    },
    addCluster() {
      // 拿到上传时间，显示在table中
      let date = new Date();
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      let time =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      // 收集提交时的时间
      const newClusterInfo = {
        clusterZhname: this.uploadInfo.clusterZhname,
        clusterUrl: this.uploadInfo.clusterUrl,
        clusterDescription: this.uploadInfo.clusterDescription,
        updateTime: time, // 将当前时间添加到新集群信息中
      };
      this.lookInfo.updateTime = time;
      // 检验输入内容是否匹配
      if (!this.namePattern.test(this.uploadInfo.clusterZhname)) {
        this.$message.error(
          "请输入正确格式的集群名称（中文、字母、数字且长度小于24）"
        );
        return;
      }
      if (!this.addressPattern.test(this.uploadInfo.clusterUrl)) {
        this.$message.error("请输入正确格式的集群地址（IP地址格式）");
        return;
      }
      if (!this.descriptionPattern.test(this.uploadInfo.clusterDescription)) {
        this.$message.error(
          "请输入正确格式的集群描述（中文名称且长度小于128）"
        );
        return;
      }
      // 推入新创建的对象
      // this.tableData.push(newClusterInfo);
      // 清空输入框
      this.nameInput = "";
      this.addressInput = "";
      this.descriptionInput = "";

      // 关闭对话框
      // this.uploadInfo.file = this.fileList[0];
      // if (!this.uploadInfo.file) {
      //   this.$message.error("请上传配置文件");
      //   return false;
      // } else {
      //   this.closeUploadDialog();
      this.$refs.uploadForm.validate((valid) => {
        // if (this.uploadInfo.file) {
        console.log(this.uploadInfo);
        if (valid) {
          this.$clusterManageApi
            .uploadAddCluster(this.uploadInfo)
            .then((res) => {
              if (res && res.code === 200) {
                this.$message.success("添加成功");
                this.getAllClusterByPage();
                this.uploadDialogVisible = false;
                // 清空数据
                // this.fileList = [];
                this.uploadInfo = {
                  clusterZhname: "",
                  clusterUrl: "",
                  clusterDescription: "",
                  // file: null,
                };
              }
            })
            .catch((error) => {
              this.$message.error("添加失败：" + error.message);
            });
        } else {
          this.$message.error("请检查数据");
          return false;
        }
        // } else {
        //   return false;
        // }
      });
      // }
    },
    refreshPage() {
      this.searchInput = "";
      this.getAllClusterByPage();
      this.$message.success("页面已刷新");
    },
    // beforeCloseUploadDialog(done) {
    //   this.$confirm('确认关闭？')
    //     .then(_ => {
    //       this.fileList = [];
    //       done()
    //     })
    //     .catch(_ => {
    //     })
    // },
    beforeCloseUploadDialog(done) {
      this.uploadInfo = {
        clusterZhname: "",
        clusterUrl: "",
        clusterDescription: "",
        // file: null,
        clusterToken: "",
      };
      done();
    },
    beforeCloseUpdateDialog(done) {
      this.fileList = [];
      done();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    openTipDialog() {
      this.openTokenDialog = true;
      console.log(1111);
    },
    // 获取创建模式
    getCreateModel(isAuto) {
      const statusMap = {
        // 0启用，1禁用
        0: "自动注册",
        1: "手动注册",
      };
      return statusMap[isAuto] || "未知状态";
    },
  },
  mounted() {
    this.getAllClusterByPage();
  },
};
</script>

<style scoped>
.cluster-detail {
  display: flex;
  justify-content: center;
  background-color: #d3e3fd;
  border: 1px solid #b8b4db;
  width: 90%;
  line-height: 30px;
  margin-left: 4%;
  margin-bottom: 10px;
}

.cluster-operate {
  background-color: #f9fbfd;
  /* border-radius:20px; */
  padding: 10px 0;
}

.keyword {
  color: #7d7575;
  font-weight: bold;
  margin-right: 5px;
  padding-left: 10px;
}

.cluster-info {
  margin-top: 10px;
  background-color: transparent;
}

.right-menu {
  display: inline;
  float: right;
  margin-right: 10px;
}

.delete-button {
  transition: opacity 0.5s ease; /* 使用 opacity 进行过渡，持续时间为 0.5 秒，缓动函数为 ease */
  opacity: 0; /* 初始状态为隐藏 */
}

.delete-button-show {
  opacity: 1; /* 显示状态 */
}

.cluster-table {
  /* width: 100%; */
  /* margin: 10px; */
  border: radius 40x;
  /* box-shadow: 1px 1px 9px #888888; */
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.upload {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.uploadDiv {
  padding-left: 14px;
}

.el-icon-arrow-down {
  font-size: 12px;
}

::v-deep .el-input {
  width: 50%;
  margin-top: 4px;
  color: #7d7575;
}

::v-deep .el-table thead {
  font-size: initial;
  color: #606266;
  font-weight: 500;
}

::v-deep .el-image {
  margin-left: 20px;
}

::v-deep .el-input--suffix {
  width: 90%;
  margin-bottom: 5px;
  color: #7d7575;
}

::v-deep .el-button {
  border-radius: 30px;
  display: inline-block;
  margin: 0 8px;
}

::v-deep .el-dialog__title {
  line-height: 24px;
  font-size: 28px;
  color: #303133;
}

::v-deep .el-dialog {
  overflow: auto;
}

::v-deep .el-upload {
  display: block;
}

::v-deep .el-pagination__total {
  color: #7d7575;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #304156;
}
</style>

<style>
.tooltipClass {
  max-width: 300px;
}
</style>
